package com.kfm.wiki.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.service.UserService;
import com.kfm.wiki.util.PageReq;
import com.kfm.wiki.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    private Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    public R list(User user, @Valid PageReq page){
        Page<User> list = userService.page(user, page);
        return R.ok(list.toPageInfo());
    }

    @PostMapping("/save")
    public R save(@RequestBody @Valid User user){
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        boolean flag = userService.save(user);
        if (flag) {
            return R.ok("保存成功");
        }
        return R.fail("保存失败");
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id){
        boolean flag = userService.removeById(id);
        if (flag) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败");
    }

    @PostMapping("/reset-pass")
    public R resetPassword(@RequestBody User user){
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.resetPassword(user);
        return R.ok("重置成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody User user){
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User login = userService.login(user);
        Long token = IdUtil.getSnowflakeNextId();
        redisTemplate.opsForValue().set(token.toString(), login, 3600 * 24, TimeUnit.SECONDS);

        login.setToken(token.toString());
        return R.ok(login);
    }

    @GetMapping("/logout/{token}")
    public R login(@PathVariable("token") Long token){
        redisTemplate.delete(token);
        LOG.info(" 删除 redis 中的 {}", token);
        return R.ok("退出成功");
    }
}
